package com.ruoyi.manager.interceptor;

import com.ruoyi.manager.properties.JwtProperties;
import com.ruoyi.manager.utils.BaseTextUtil;
import com.ruoyi.manager.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {


    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拦截 user相关请问请求
        System.out.println("拦截用户请求");

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //解析token
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //2、校验令牌
        try {
            System.out.println("当前令牌为：" + token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);

            Long memberId = Long.valueOf(claims.get("memberId").toString());

            //存入到线程变量中
            System.out.println("当前用户id为：" + memberId);
            BaseTextUtil.setCurrentId(memberId);


            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(410);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在控制器方法执行之后，视图渲染之前执行
    }

}
